<?php
namespace AuctionCore\Fours;

use AuctionCore\System\AuctionException;
use Think\Exception;
use Think\Log;

/**
 * 4s店
 *
 * @author
 */
class Fours
{
    private $FoursBankAccount;

    public function __construct()
    {
        $this->FoursBankAccount = M('fours_bank_account');
    }

    //获取4s店列表
    public function getFoursList($page, $limit, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $limit = (int)$limit < 1 ? 10 : (int)$limit;
        //搜索
        $map = array();
        //查询条件
        if (!empty($params['search_key'])) {
            $map['u.user_name'] = array('like', '%' . $params['search_key'] . '%');
            $map['fu.real_name'] = array('like', '%' . $params['search_key'] . '%');
            $map['fu.phone'] = array('like', '%' . $params['search_key'] . '%');
            $map['f.f_name'] = array('like', '%' . $params['search_key'] . '%');
            $map['_logic'] = 'or';
        }
        // if (!empty($params['city'])) {
        //     $map['f.city'] = array('in',$params['city']);
        // }
        //要查询的列
        $cols = "u.user_name,fu.real_name,u.status,fu.phone,u.uid,fu.fu_id,f.f_name";
        $prefix = C("DB_PREFIX");
        $total = M('user')->alias('u')
            ->join("inner JOIN {$prefix}fours_user as fu ON fu.u_id = u.uid")
            ->join("LEFT JOIN {$prefix}fours f ON f.fid= fu.f_id")
            ->where($map)->count();
        $list = M('user')->alias('u')->field($cols)
            ->join("inner JOIN {$prefix}fours_user as fu ON fu.u_id = u.uid")
            ->join("LEFT JOIN {$prefix}fours f ON f.fid= fu.f_id")
            ->where($map)->limit($limit)->page($page)->select();
        // echo M()->getLastSql();
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    //获取集团列表
    public function getBlocList($page, $limit, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $limit = (int)$limit < 1 ? 10 : (int)$limit;
        //搜索
        $map = array();
        //查询条件
        if (!empty($params['search_key'])) {
            $map['u.user_name'] = array('like', '%' . $params['search_key'] . '%');
            $map['bu.real_name'] = array('like', '%' . $params['search_key'] . '%');
            $map['bu.phone'] = array('like', '%' . $params['search_key'] . '%');
            $map['b.b_name'] = array('like', '%' . $params['search_key'] . '%');
            $map['_logic'] = 'or';
        }

        //要查询的列
        $cols = "u.uid,u.user_name,u.status,bu.real_name,bu.phone,bu.bu_id,b.b_name";

        $prefix = C("DB_PREFIX");
        $total = M('user')->alias('u')->field($cols)
            ->join("inner JOIN {$prefix}bloc_user as bu on u.uid = bu.u_id ")
            ->join("LEFT JOIN {$prefix}bloc as b ON b.bid = bu.b_id")
            ->where($map)->count();
        $list = M('user')->alias('u')->field($cols)
            ->join("inner JOIN {$prefix}bloc_user as bu on u.uid = bu.u_id ")
            ->join("LEFT JOIN {$prefix}bloc as b ON b.bid = bu.b_id")
            ->where($map)->limit($limit)->page($page)->select();
        // echo M()->getLastSql();
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**
     *获取所有4S店信息
     **/
    public function getAllFours()
    {
        return M('fours')->field('fid,f_name')->select();
    }

    /**
     *获取指定城市下的4s信息
     **/
    public function getFoursCity($city)
    {
        $map = array();
        $map['city'] = array('in', $city);
        return M('fours')->field('fid,f_name')->where($map)->select();
    }

    /**
     *获取所有集团信息
     **/
    public function getAllBloc()
    {
        return M('bloc')->field('bid,b_name')->select();
    }

    /**
     * 查找4s店账号信息
     *
     * @param $id
     * @return mixed'
     */
    public function getOneFours($id)
    {
        $prefix = C("DB_PREFIX");
        $cols = "u.user_name,fu.real_name,fu.phone,u.uid,f.fid,f.f_name,f.addr as faddr,f.city";
        $list = M('user')->alias('u')->field($cols)
            ->join("inner JOIN {$prefix}fours_user as fu ON fu.u_id = u.uid")
            ->join("LEFT JOIN {$prefix}fours f ON f.fid= fu.f_id")
            ->where('u.uid =' . $id)->find();
        return $list;
    }

    /**
     * 查找指定集团账号信息
     * @param $uid
     * @return mixed
     */
    public function getOneBloc($uid)
    {
        $prefix = C("DB_PREFIX");
        $cols = "u.user_name,bu.real_name,bu.phone,u.uid,b.b_name,b.addr,b.bid";
        $list = M('user')->alias('u')->field($cols)
            ->join("inner JOIN {$prefix}bloc_user as bu ON bu.u_id = u.uid")
            ->join("LEFT JOIN {$prefix}bloc as b ON b.bid = bu.b_id")
            ->where('u.uid =' . $uid)->find();
        return $list;
    }

    /**
     * 添加4S账号信息
     *
     * @param $user
     * @param $fu
     * @return bool|mixed
     */
    public static function create($user, $fu)
    {
        try {
            //开启事务
            M()->startTrans();
            //添加用户
            $uid = M('user')->add($user);
            //添加到4s组
            M('auth_group_access')->add(array('uid' => $uid, 'group_id' => 4));
            //添加4s店对应用户记录
            $fu['u_id'] = $uid;
            M('fours_user')->add($fu);
            M()->commit();
            return $uid;
        } catch (\Exception $e) {
            M()->rollback();
            Log::record("添加4S店账号失败，ERROR_MSG：" . $e->getMessage(), "ERR", true);
            return false;
        }
    }

    /**
     * 添加集团账号信息
     * @param $user
     * @param $bu
     * @return bool|mixed
     */
    public static function createBloc($user, $bu)
    {
        try {
            //开启事务
            M()->startTrans();
            //添加用户
            $uid = M('user')->add($user);
            //添加到集团组
            M('auth_group_access')->add(array('uid' => $uid, 'group_id' => 5));
            //添加集团对应用户记录
            $bu['u_id'] = $uid;
            M('bloc_user')->add($bu);
            M()->commit();
            return $uid;
        } catch (\Exception $e) {
            M()->rollback();
            Log::record("添加集团账号失败，ERROR_MSG：" . $e->getMessage(), "ERR", true);
            return false;
        }
    }

    /**
     * 账号启用分组
     * @param int $uid
     */
    public function enable($uid)
    {
        if ($uid < 1) {
            return false;
        }
        $ok = M('user')->where(array('uid' => $uid))->save(array('status' => '0'));
        Log::record(M()->_sql(), "ERR", true);
        return $ok;
    }

    /**
     *  4s店账号禁用分组
     * @param $uid
     */
    public function disable($uid)
    {
        if ($uid < 1) {
            return false;
        }
        $ok = M('user')->where(array('uid' => $uid))->save(array('status' => '1'));
        Log::record(M()->_sql(), "ERR", true);
        return $ok;
    }

    /**
     * 添加4S信息
     */
    // public static function createBf($post_fb,$b_id)
    // {
    //     foreach ($post_fb as $key => $value) {
    //         $map = array();
    //         $map['b_id'] = $b_id;
    //         $map['modifytime'] = date('Y-m-d H:i:s');
    //         $ok = M('fours')->where("id = '$value'")->save($map);
    //     }
    //     return $ok;
    // }

    /**
     * 修改4S信息
     * @param $user
     * @param $fu
     * @return bool
     */
    public static function update($user, $fu)
    {
        $uid = array_shift($user);
        try {
            //开启事务
            M()->startTrans();
            //修改用户
            $ok = M('user')->where(array("uid" => $uid))->save($user);
            //修改用户对应4s店表
            M('fours_user')->where(array("uid" => $uid));
            M()->commit();
            return $ok;
        } catch (\Exception $e) {
            M()->rollback();
            return false;
        }
    }

    /**
     * 修改集团信息
     * @param $user
     * @param $bu
     * @return bool
     */
    public static function updateBloc($user, $bu)
    {
        $uid = array_shift($user);
        try {
            //开启事务
            M()->startTrans();
            //修改用户
            $ok = M('user')->where(array('uid' => $uid))->save($user);
            //修改用户对应集团表
            M('bloc_user')->where(array('u_id' => $uid))->save($bu);
            M()->commit();
            return $ok;
        } catch (\Exception $e) {
            M()->rollback();
            return false;
        }
    }


    public function restPwd($uid)
    {
        if (intval($uid) < 1) {
            AuctionException::make_throw('1000001');
        }
        $ok = M('user')->where(array('uid' => $uid))->save(array('passwd' => md5('123456')));
        Log::record(M()->_sql(), "ERR", true);
        return $ok;
    }

    /***********************************************集团及4S店管理**********************************************************/


    /**
     * 集团列表
     *
     * @param $page
     * @param $limit
     * @param $params
     *
     * @return array
     */
    public function get_bmanger_list($page, $limit, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $limit = (int)$limit < 1 ? 10 : (int)$limit;
        //搜索
        $map = array();
        //查询条件
        if (!empty($params['search_key'])) {
            $map['b.b_name'] = array('like', '%' . $params['search_key'] . '%');
            $map['b.addr'] = array('like', '%' . $params['search_key'] . '%');
            $map['b.contact'] = array('like', '%' . $params['search_key'] . '%');
            $map['b.phone'] = array('like', '%' . $params['search_key'] . '%');
            $map['_logic'] = 'or';
        }

        $prefix = C("DB_PREFIX");
        $total = M('bloc')->alias('b')->field("b.*")
            ->join("LEFT JOIN {$prefix}fours as f ON f.b_id = b.bid")
            ->where($map)->group('b.bid')->select();
        $total = count($total);
        $list = M('bloc')->alias('b')->field("b.*")
            ->join("LEFT JOIN {$prefix}fours as f ON f.b_id = b.bid")
            ->where($map)->group('b.bid')->limit($limit)->page($page)->select();
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**
     * @param $page
     * @param $limit
     * @param $params
     *
     * @return array
     */
    public function get_fmanger_list($page, $limit, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $limit = (int)$limit < 1 ? 10 : (int)$limit;
        //搜索 
        $map = array();
        $where = array();
        if ($params['user_id']) {
            $where['f.developer'] = array('eq', $params['user_id']);
        }
        //集团管理-下属4s店 传过来的bid
        if ($params['bid']) {
            $where['b.bid'] = array('eq', $params['bid']);
        }
        if (!empty($params['bc_city'])) {
            $where['f.city'] = array('IN', $params['bc_city']);
        }
        //查询条件
        if (!empty($params['search_key'])) {
            $map['f.f_name'] = array('like', '%' . $params['search_key'] . '%');
            $map['f.addr'] = array('like', '%' . $params['search_key'] . '%');
            $map['f.contact'] = array('like', '%' . $params['search_key'] . '%');
            $map['f.phone'] = array('like', '%' . $params['search_key'] . '%');
            $map['f.developer'] = array('like', '%' . $params['search_key'] . '%');
            $map['b.b_name'] = array('like', '%' . $params['search_key'] . '%');
            $map['_logic'] = 'or';
            $where['_complex'] = $map;
        }
        //要查询的列
        $cols = "f.fid,f.f_name,f.addr,f.contact,f.phone,f.developer,b.b_name,f.city,e.real_name";

        $prefix = C("DB_PREFIX");
        $total = M('fours')->alias('f')
            ->join("LEFT JOIN {$prefix}bloc as b ON f.b_id = b.bid")
            ->join("LEFT JOIN {$prefix}employee as e ON e.emp_id = f.developer")
            ->where($where)->count();
        $list = M('fours')->alias('f')->field($cols)
            ->join("LEFT JOIN {$prefix}bloc as b ON f.b_id = b.bid")
            ->join("LEFT JOIN {$prefix}employee as e ON e.emp_id = f.developer")
            ->where($where)->limit($limit)->page($page)->select();
        // echo M()->getLastSql();
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;

    }

    public function createbm($bloc)
    {

        //添加
        $bid = M('bloc')->add($bloc);

        return $bid;
    }

    /**
     * 添加4S店
     *
     * @param $fours
     * @param $bank_account
     * @param $come_from
     *
     * @return bool|mixed
     */
    public function createfm($fours, $bank_account, $come_from)
    {

        //开启事务
        M()->startTrans();
        //添加渠道
        $c_id = M('come_from')->add($come_from);

        $fours['channel_id'] = $c_id;
        //添加4s店
        $f_id = M('fours')->add($fours);
        //添加4s店账户信息
        if ($this->is_two_array($bank_account)) {
            foreach ($bank_account as $kb => $va) {
                $va['fid'] = $f_id;
                $bank_account_id = $this->FoursBankAccount->add($va);
            }
        } else {
            $bank_account['fid'] = $f_id;
            $bank_account_id = $this->FoursBankAccount->add($bank_account);
        }

        //出错回滚
        if ($c_id < 1 || $f_id < 1 || $bank_account_id < 1) {

            M()->rollback();

            return false;
        }
        M()->commit();

        return $f_id;
    }

    /**
     * 判断是否二维数组
     *
     * @param $array
     *
     * @return bool
     */
    function is_two_array($array)
    {
        $s = false;
        foreach ($array as $value) {
            if (is_array($value)) {
                $s = true;
            }
        }
        return $s;
    }

    public function find_bloc($bid)
    {
        return M('bloc')->where(array('bid' => $bid))->find();
    }

    public function find_fours($fid)
    {
        $cols = "f.*,b.b_name,b.bid";
        $prefix = C("DB_PREFIX");
        $list = M('fours')->alias('f')->field($cols)
            ->join("LEFT JOIN {$prefix}bloc as b ON f.b_id = b.bid")
            ->where(array('fid' => $fid))->find();
        return $list;
    }

    public function updatebm($bloc, $bid)
    {

        return $ok = M('bloc')->where("bid = '$bid'")->save($bloc);

    }

    public function updatefm($fours, $fid)
    {
        //开启事务
        M()->startTrans();
        //修改4s店
        $f_id = M('fours')->where("fid = '$fid'")->save($fours);
        //修改渠道
        $c_id = M('come_from')->where("from_id = '$fours[channel_id]'")->save(array('from_name' => $fours['f_name']));

        if ($f_id < 1) {

            M()->rollback();

            return false;
        }
        M()->commit();

        return $f_id;
    }

    /**
     *   获取指定集团已绑定的4s店id
     **/
    public function get_spm($bid)
    {
        return M('fours')->field('fid')->where("b_id='$bid'")->select();
    }

    public function set_spm($bid, $fid)
    {
        $ok = M('fours')->where("fid='$fid'")->save(array('b_id' => $bid));
    }

    public function exgraft_spm($bid, $fid)
    {
        $ok = M('fours')->where("fid='$fid'")->save(array('b_id' => 0));
    }


    /**
     *指定条件获取4s店信息
     */
    public function get_fours_info($map)
    {
        return M('fours')->where($map)->find();
    }

    /**
     * 添加4s店对应打款帐号
     *
     * @param array $data
     * return array
     */
    public function add_bank_acount($data)
    {
        if (empty($data)) {
            return false;
        }
        return $this->FoursBankAccount->add($data);
    }

    /**
     * 添加4s店对应打款帐号
     *
     * @param array $data
     * return array
     */
    public function update_bank_acount($data)
    {
        if (empty($data)) {
            return false;
        }
        return $this->FoursBankAccount->save($data);
    }

    /**
     * 获取4s店对应打款帐号
     *
     * @param int $fid
     * return array
     */
    public function get_bank_account_by_fid($fid)
    {
        if ($fid < 1) {
            return false;
        }
        $condition['fid'] = ['eq', $fid];
        return $this->FoursBankAccount->where($condition)->select();
    }

    /**
     * 获取4s店信息完整的打款帐号
     *
     * @param $fid
     *
     * @return array|bool
     */
    public function get_bank_account_list_by_fid($fid)
    {
        if ($fid < 1) {
            return false;
        }
        $condition['fid'] = ['eq', $fid];
        $list = $this->FoursBankAccount->where($condition)->select();
        $list_data = [];
        if (!empty($list)) {
            foreach ($list as $key => $val) {
                if (!empty($val['card_no']) &&
                    !empty($val['account_name']) &&
                    !empty($val['bank_name'])
                ) {
                    $list_data[$key]['id'] = $val['id'];
                    $list_data[$key]['fid'] = $val['fid'];
                    $list_data[$key]['card_no'] = $val['card_no'];
                    $list_data[$key]['account_name'] = $val['account_name'];
                    $list_data[$key]['bank_name'] = $val['bank_name'];
                    $list_data[$key]['createtime'] = $val['createtime'];
                }
            }
        }
        return $list_data;
    }
}